package com.jason.kotlin.meta.architecture2.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.jason.kotlin.meta.architecture2.api.ApiSource
import com.jason.kotlin.meta.architecture2.api.ProjectService
import com.jason.kotlin.meta.architecture2.model.ArticleBean
import com.jason.kotlin.meta.architecture2.model.ClassifyBean
import com.jason.kotlin.meta.architecture2.model.WanDataWrapper
import com.jason.kotlin.meta.architecture2.repository.ProjectApi
import com.jason.kotlin.meta.architecture2.repository.ProjectApiImpl
import com.jason.library.common.base.PageStatus
import kotlinx.coroutines.launch
import java.lang.Exception

class ProjectViewModel(application: Application) : AndroidViewModel(application){

    //页面状态变化
    val pageStatusData = MutableLiveData<PageStatus>()

    val classifyData = MutableLiveData<WanDataWrapper<List<ClassifyBean>>>()

    val articleData = MutableLiveData<WanDataWrapper<List<ArticleBean>>>()

    private var projectApi : ProjectApi

    private var curPage: Int = 0

    init {

        val projectService = ApiSource.getWanAndroidService(ProjectService::class.java)
        projectApi = ProjectApiImpl(projectService)
    }

    fun loadProjectClassify() {
        viewModelScope.launch {
            pageStatusData.postValue(PageStatus.loading())
            try {
                val classifyResponse = projectApi.getProjectClassify()

                classifyData.postValue(WanDataWrapper.success(classifyResponse.data))

                pageStatusData.postValue(PageStatus.success())
            }catch (e: Exception) {
                pageStatusData.postValue(PageStatus.error(e.toString()))
            }
        }
    }

    fun loadArticleData(cid: Int) {
        curPage = 0
        loadData(cid)
    }

    fun loadArticleMoreData(cid: Int) {
        curPage++
        loadData(cid)
    }

    fun loadData(cid: Int) {
        viewModelScope.launch {
            pageStatusData.postValue(PageStatus.loading())
            try {
                val articleResponse = projectApi.getProjectList(curPage, cid)
                articleData.postValue(WanDataWrapper.success(articleResponse.data.datas))

                pageStatusData.postValue(PageStatus.success())
            }catch (e:Exception) {
                pageStatusData.postValue(PageStatus.error(e.toString()))
            }
        }
    }
}